package com.yeqian.user.security;

import com.yeqian.user.entity.LoginConstant;
import com.yeqian.user.entity.UserInfo;
import com.yeqian.user.mapper.RoleInfoMapper;
import com.yeqian.user.service.UserInfoService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class YeqUserDetailService implements UserDetailsService {
    /**
     * 查询用户信息的接口
     */
    @Resource
    private UserInfoService userInfoService;

    @Resource
    private RoleInfoMapper roleInfoMapper;

    /**
     * @Description 根据用户的name进行操作
     * @Date 2021/4/29 17:30
     */
    @Override
    public UserDetails loadUserByUsername(String username) {

        UserInfo userInfo = userInfoService.getUserByName(username);
        if (userInfo == null) {
            //说明用户名不存在
            throw new UsernameNotFoundException(LoginConstant.USERNAME_DOES_NOT_EXIST);
        }
        // 设置权限
        String Role = roleInfoMapper
                .getUserRoleById(userInfo.getId())
                .stream().collect(Collectors.joining(","));
        List<GrantedAuthority> role = AuthorityUtils.commaSeparatedStringToAuthorityList(Role);
        return new User(username, userInfo.getPassword(), role);
    }
}
